package com.jhgsys.internal.common.utils;

import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.*;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * Plupload是一个上传插件。
 * 上传原理为单个文件依次发送至服务器.
 * 上传大文件时可以将其碎片化上传。但是一般情况下，不会这样做，
 * 所以这里更多的是处理普通文件的批量上传。
 * 这里主要处理文件上传
 */
public class PluploadUtil {
    private static final int BUF_SIZE = 2 * 1024;
    private static final String[] imageFiles = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };
    /**
     * 用于Plupload插件的文件上传
     * @param plupload - 存放上传所需参数的bean
     * @param dir - 保存目标文件目录
     * @throws IllegalStateException
     * @throws IOException
     */
    public static void upload(Plupload plupload, File dir) throws IllegalStateException, IOException {
        String finalName = MD5Util.encrypt(plupload.getName(), "123456");
        int chunks = plupload.getChunks();  //获取总的碎片数
        int chunk = plupload.getChunk();    //获取当前碎片(从0开始计数)

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) plupload.getRequest();
        MultiValueMap<String, MultipartFile> map = multipartRequest.getMultiFileMap();

        if(map != null) {
            if (!dir.exists()) {dir.mkdirs();}    //如果目标文件夹不存在则创建新的文件夹
            //事实上迭代器中只存在一个值,所以只需要返回一个值即可
            Iterator<String> iter = map.keySet().iterator();
            while(iter.hasNext()) {
                String str = iter.next();
                List<MultipartFile> fileList =  map.get(str);
                for(MultipartFile multipartFile : fileList) {
                    //因为只存在一个值,所以最后返回的既是第一个也是最后一个值
                    plupload.setMultipartFile(multipartFile);

                    //创建新目标文件
                    String originFileName = plupload.getName();
                    // 获取后缀名
                    String suffix = getFileSuffix(originFileName);
                    //生成唯一的文件名
                    String targetFileName = FebsUtil.uuid() + suffix;
                    plupload.setFileName(targetFileName);
                    File targetFile = new File(dir.getPath()+ "/" + targetFileName);

                    //当chunks>1则说明当前传的文件为一块碎片，需要合并
                    if (chunks > 1) {
                        //需要创建临时文件名，最后再更改名称
                        File tempFile = new File(dir.getPath()+ "/" + finalName + "_" + chunk);
                        //如果chunk==0,则代表第一块碎片,不需要合并
                        //saveUploadFile(multipartFile.getInputStream(), tempFile, chunk == 0 ? false : true);
                        saveUploadFile(multipartFile.getInputStream(), tempFile, false);

                        //上传并合并完成，则将临时名称更改为指定名称
                        if (chunks - chunk == 1) {
                            //开始合并文件了
                            for (int j = 0; j < chunks; j++) {
                                int count = 0;
                                tempFile = new File(dir.getPath()+ "/" + finalName + "_" + j);
                                //文件不存在,等待10秒
                                while (!tempFile.exists() && count < 10) {
                                    try {
                                        Thread.sleep(1000);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    count++;
                                }
                                if (tempFile.exists()) {
                                    FileInputStream in = new FileInputStream(tempFile);
                                    try {
                                        saveUploadFile(in, targetFile, true);
                                    } finally {
                                        in.close();
                                        tempFile.delete();
                                    }
                                } else {
                                    System.out.println("Error File not exists!" + tempFile);
                                }
                            }
                            //压缩图片
                            compressImage(plupload, dir, multipartFile);
                        }
                    } else {
                        //否则直接将文件内容拷贝至新文件
                        multipartFile.transferTo(targetFile);
                        //压缩图片
                        compressImage(plupload, dir, multipartFile);
                    }
                }
            }
        }
    }

    private static void compressImage(Plupload plupload, File dir, MultipartFile multipartFile) throws IOException {
        if (isImageFile(plupload.getFileName(), imageFiles)) {
            String smallFileName = getFileName(plupload.getFileName()) + "_s" + getFileSuffix(plupload.getFileName());
            plupload.setSmallFileName(smallFileName);
            compressImage(dir + "/" + plupload.getFileName(), dir + "/" + smallFileName, plupload.getWidth());
        }
    }

    private static boolean isImageFile(String fileName, String[] allowFiles) {
        Iterator<String> type = Arrays.asList(allowFiles).iterator();
        while (type.hasNext()) {
            String ext = type.next();
            if (fileName.toLowerCase().endsWith(ext)) {
                return true;
            }
        }
        return false;
    }

    private static void compressImage(String sourceFile, String smallFile, int width) throws IOException {
        //默认大图宽度
        int widthBig = 1000;
        //默认小图宽度
        int widthSmall = 200;
        if (width > 0) {
            //如果指定了压缩宽度，就采用指定宽度，比如头像
            widthBig = width;
            widthSmall = width;
        }
        // 压缩大图
        ImageUtils.zoomImage(sourceFile, sourceFile, widthBig, 0);
        // 压缩小图
        ImageUtils.zoomImage(sourceFile, smallFile, widthSmall, 0);
    }

    private static String getFileSuffix(String fileName) {
        if (StringUtils.isEmpty(fileName)) {
            return "";
        }
        if (fileName.indexOf(".") < 0) {
            return "";
        }
        return fileName.substring(fileName.lastIndexOf("."));
    }

    private static String getFileName(String fileName) {
        if (StringUtils.isEmpty(fileName)) {
            return "";
        }
        if (fileName.indexOf(".") < 0) {
            return fileName;
        }
        return fileName.substring(0, fileName.lastIndexOf("."));
    }

    /**
     * 保存上传文件，兼合并功能
     */
    private static void saveUploadFile(InputStream input, File targetFile, boolean append) throws IOException {
        OutputStream out = null;
        try {
            if (targetFile.exists() && append) {
                out = new BufferedOutputStream(new FileOutputStream(targetFile, true), BUF_SIZE);
            } else {
                out = new BufferedOutputStream(new FileOutputStream(targetFile), BUF_SIZE);
            }

            byte[] buffer = new byte[BUF_SIZE];
            int len = 0;
            //写入文件
            while ((len = input.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            //关闭输入输出流
            if (null != input) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 判断是否全部上传完成
     * 碎片需合并后才返回真
     */
    public static boolean isUploadFinish(Plupload plupload) {
        return (plupload.getChunks() - plupload.getChunk() == 1);
    }

}
